package com.projectnection.server.database.liveFeed;

import java.util.Arrays;
import java.util.List;

import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.googlecode.objectify.Objectify;
import com.projectnection.server.database.ObjectifyServiceCreation;
import com.projectnection.server.database.entities.GetEntity;
import com.projectnection.server.model.Entity;
import com.projectnection.server.model.LiveFeed;

public class ListLiveFeeds {

	public static JSONArray jsonListLiveFeeds(String entityID) {

		Entity entity = GetEntity.get(entityID);

		return jsonListLiveFeeds(list(entity));
	}

	public static LiveFeed[] list(Entity entity) {

		Objectify objfyService = ObjectifyServiceCreation.gerService();

		List<LiveFeed> liveFeedListFrom = objfyService.query(LiveFeed.class)
				.filter("entityIDFrom", entity).order("-liveFeedDate").list();

		List<LiveFeed> liveFeedListTo = objfyService.query(LiveFeed.class)
				.filter("entityIDTo", entity).order("-liveFeedDate").list();

		liveFeedListFrom.addAll(liveFeedListTo);

		LiveFeed[] liveFeedArray = new LiveFeed[liveFeedListFrom.size()];

		liveFeedListFrom.toArray(liveFeedArray);

		Arrays.sort(liveFeedArray);

		return liveFeedArray;
	}

	// SaveLiveFeed
	// .addNew(SaveLiveFeed
	// .loadLiveFeed(
	// "LiveSource",
	// "AllineO",
	// "@AllineO created a new To Do class: SaveFeatureFile in the project @LiveSource"));

	// SaveLiveFeed
	// .addNew(SaveLiveFeed
	// .loadLiveFeed(
	// "LiveSource",
	// "AaronVonderHaar",
	// "@AaronVonderHaar created a new To Do class: ListFeatureFiles in the project @LiveSource"));

	public static JSONArray jsonListLiveFeeds(LiveFeed[] liveFeeds) {

		JSONArray jsonLiveFeeds = new JSONArray();

		for (LiveFeed liveFeed : liveFeeds) {

			jsonLiveFeeds.put(jsonLiveFeed(liveFeed));
		}

		return jsonLiveFeeds;
	}

	public static JSONObject jsonLiveFeed(LiveFeed liveFeed) {

		JSONObject jsonFeed = null;

		try {

			jsonFeed = new JSONObject();

			jsonFeed.put("liveFeedID", liveFeed.getLiveFeedID());

			jsonFeed.put("entityIDFrom", liveFeed.getEntityIDFrom().getName());

			jsonFeed.put("entityIDTo", liveFeed.getEntityIDTo().getName());

			jsonFeed.put("liveFeedDate", liveFeed.getLiveFeedDate().getTime());

			jsonFeed.put("liveFeedDescription",
					liveFeed.getLiveFeedDescription());

		} catch (JSONException e) {

			e.printStackTrace();
		}

		return jsonFeed;
	}

}